<?php

if (!defined('BASE_PATH'))
	exit('Restricted access');

class mysqlDatabase extends Database {

	// 查询数据 #TODO 查询字串过滤
	public function query() {
		if (!is_resource($this->conn_id)) {
			return false;
		}

		$sql = $this->_sql;

		if ($this->_limit > 0 || $this->_offset > 0) {
			$sql .= ' LIMIT ' . max($this->_offset, 0) . ', ' . max($this->_limit, 0);
		}

		if ($this->debug) {
			$this->_log[] = $sql;
		}
		$this->_error_msg = '';
		$this->_cursor = mysql_query($sql, $this->conn_id);

		if (!$this->_cursor) { 
			$this->_errorNum = mysql_errno($this->conn_id);
			$this->_error_msg = array(
				"errorNum:" . mysql_errno($this->conn_id),
				mysql_error($this->conn_id) . " SQL=$sql"
			);
			if ($this->debug) {
				show_error($this->_error_msg);
			}
			return false;
		}

		return $this->_cursor;
	}

	/**
	 * 将所有结果作为关联数组返回
	 */
	public function get_all() {
		// 查询失败，未得到返回资源句柄
		if (!($cur = $this->query())) {
			return null;
		}

		// 逐行获取结果集中所有数据，拼装成关联数组
		$result = array();
		while ($row = mysql_fetch_assoc($cur)) {
			$result[] = $row;
		}

		mysql_free_result($cur);

		return $result;
	}

	/**
	 * 从结果集中取得一行作为关联数组
	 */
	public function get_row() {
		// 查询失败，未得到返回资源句柄
		if (!($cur = $this->query())) {
			return null;
		}

		// 获取第一行数据，并返回
		$result = null;
		if ($array = mysql_fetch_assoc($cur)) {
			$result = $array;
		}

		mysql_free_result($cur);

		return $result;
	}

	/**
	 * 获取结果集中第一条记录第一个字段的值
	 * 
	 * @see Database::get_one()
	 */
	public function get_one() {
		// 查询失败，未得到返回资源句柄
		if (!($cur = $this->query())) {
			return null;
		}

		$result = null;
		if ($row = mysql_fetch_row($cur)) {
			$result = $row[0];
		}

		mysql_free_result($cur);

		return $result;
	}

	/**
	 * 插入数据
	 * 
	 * @param string $table
	 * @param array $data
	 */
	public function insert($table, &$data) {

		$insert_info = $this->get_insert_info($data);

		$sql = 'INSERT INTO ' . $table . ' ' . $insert_info['fields'] . ' VALUES ' . $insert_info['values'];

		$this->set_query($sql);

		if (!$this->query()) {
			return false;
		}

		return true;
	}

	/**
	 * 执行更新记录操作
	 * @param $data 		要更新的数据内容，参数可以为数组也可以为字符串，建议数组。
	 * 						为数组时数组key为字段值，数组值为数据取值
	 * 						为字符串时[例：`name`='phpcms',`hits`=`hits`+1]。
	 * 						为数组时[例: array('name'=>'phpcms','password'=>'123456')]
	 * 						数组可使用array('name'=>'+=1', 'base'=>'-=1');程序会自动解析为`name` = `name` + 1, `base` = `base` - 1
	 * @param $table 		数据表
	 * @param $where 		更新数据时的条件
	 * @return boolean
	 */
	public function update($table, &$data, $where) {

		if ($table == '' or $where == '') {
			return false;
		}

		$where = ' WHERE ' . $where;
		$field = '';
		if (is_string($data) && $data != '') {
			$field = $data;
		} elseif (is_array($data) && count($data) > 0) {
			$fields = array();
			foreach ($data as $k => $v) {
				switch (substr($v, 0, 2)) {
					case '+=':
						$v = substr($v, 2);
						if (is_numeric($v)) {
							$fields[] = $this->add_special_char($k) . '=' . $this->add_special_char($k) . '+' . $this->escape_string($v, '', false);
						} else {
							continue;
						}

						break;
					case '-=':
						$v = substr($v, 2);
						if (is_numeric($v)) {
							$fields[] = $this->add_special_char($k) . '=' . $this->add_special_char($k) . '-' . $this->escape_string($v, '', false);
						} else {
							continue;
						}
						break;
					default:
						$fields[] = $this->add_special_char($k) . '=' . $this->escape_string($v);
				}
			}
			$field = implode(',', $fields);
		} else {
			return false;
		}

		$sql = 'UPDATE ' . $table . ' SET ' . $field . $where;

		$this->set_query($sql);

		if (!$this->query()) {
			return false;
		}

		return true;
	}

	protected function db_connect() {
		if ($this->port != '') {
			$this->hostname .= ':' . $this->port;
		}

		if (!($this->conn_id = @mysql_connect($this->hostname, $this->username, $this->password, true))) {
			$this->_error_msg = 'Could not connect to MySQL';
		}

		return;
	}

	protected function db_pconnect() {
		if ($this->port != '') {
			$this->hostname .= ':' . $this->port;
		}

		if ((!$this->conn_id = @mysql_pconnect($this->hostname, $this->username, $this->password))) {
			$this->_error_msg = 'Could not connect to MySQL';
		}

		return;
	}

	protected function db_select() {
		if (!mysql_select_db($this->database, $this->conn_id)) {
			$this->_error_msg = 'Could not connect to database';

			return false;
		}

		return true;
	}

	protected function db_set_charset($charset, $collation) {
		return @mysql_query("SET NAMES '" . $charset . "' COLLATE '" . $collation . "'", $this->conn_id);
	}

	/**
	 * 对字段两边加反引号，以保证数据库安全
	 * @param $value 数组值
	 */
	public function add_special_char(&$value) {
		if ('*' == $value || false !== strpos($value, '(') || false !== strpos($value, '.') || false !== strpos($value, '`')) {
			//不处理包含* 或者 使用了sql方法。
		} else {
			$value = '`' . trim($value) . '`';
		}
		return $value;
	}

	/**
	 * 对字段值两边加引号，以保证数据库安全
	 * @param $value 数组值
	 * @param $key 数组key
	 * @param $quotation
	 */
	public function escape_string(&$value, $key = '', $quotation = 1) {
		if ($quotation) {
			$q = '\'';
		} else {
			$q = '';
		}
		$value = $q . $value . $q;
		return $value;
	}

}